package edu.fit5046.mymonashmate.activity;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import edu.fit5046.mymonashmate.R;
import edu.fit5046.mymonashmate.utils.DetailInfo;
import edu.fit5046.mymonashmate.utils.HttpUtils;
import edu.fit5046.mymonashmate.utils.SimpleInfo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateActivity extends Activity implements OnClickListener {
	public static final String TAG = "Info";
	public static final int INFO_END = DetailInfo.INFO_PREVIOUSJOB + 1;
	public static final String url = "/entity.mymonashmates";
	public static final String url3 = "/entity.idunits";
	private EditText editTextRegInfo[];
	private static final String inv = "1Nvi5IblE";
	private static final int unitNumber = 10;
	private boolean[] checkResult;
	private boolean[] ischecked;
	CheckBox box0;
	CheckBox box1;
	CheckBox box2;
	CheckBox box3;
	CheckBox box4;
	CheckBox box5;
	CheckBox box6;
	CheckBox box7;
	CheckBox box8;
	CheckBox box9;
	DetailInfo info;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.layout_info);
		checkResult = new boolean[unitNumber];
		ischecked = new boolean[10];
		initWidget();

		// getValue from mapActivity

		// get info form networ
		info = null;
		try {
			info = getInfoFromNetwork();
		} catch (JSONException | InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		updateView(info);

		super.onCreate(savedInstanceState);
	}

	private void initWidget() {
		editTextRegInfo = new EditText[INFO_END];
		editTextRegInfo[DetailInfo.INFO_NAME] = (EditText) findViewById(R.id.text_Name);
		editTextRegInfo[DetailInfo.INFO_SURNAME] = (EditText) findViewById(R.id.text_SurName);
		editTextRegInfo[DetailInfo.INFO_COURSE] = (EditText) findViewById(R.id.text_Course);
		editTextRegInfo[DetailInfo.INFO_UNIT] = (EditText) findViewById(R.id.text_Unit);

		editTextRegInfo[DetailInfo.INFO_NATIONNANITY] = (EditText) findViewById(R.id.text_NNanity);
		editTextRegInfo[DetailInfo.INFO_FIRSTLANGUAGE] = (EditText) findViewById(R.id.text_FLanguage);
		editTextRegInfo[DetailInfo.INFO_SECONDLANGUAGE] = (EditText) findViewById(R.id.text_SLanguage);
		editTextRegInfo[DetailInfo.INFO_ADDRESS] = (EditText) findViewById(R.id.text_address);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEFOOD] = (EditText) findViewById(R.id.text_FFood);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEMOIVE] = (EditText) findViewById(R.id.text_FMovie);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEUNIT] = (EditText) findViewById(R.id.text_FUnit);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEPROLAN] = (EditText) findViewById(R.id.text_FProLanguage);
		editTextRegInfo[DetailInfo.INFO_CURRENTJOB] = (EditText) findViewById(R.id.text_CJob);
		editTextRegInfo[DetailInfo.INFO_PREVIOUSJOB] = (EditText) findViewById(R.id.text_PJob);

		box0 = (CheckBox) findViewById(R.id.box0);
		box1 = (CheckBox) findViewById(R.id.box1);
		box2 = (CheckBox) findViewById(R.id.box2);
		box3 = (CheckBox) findViewById(R.id.box3);
		box4 = (CheckBox) findViewById(R.id.box4);
		box5 = (CheckBox) findViewById(R.id.box5);
		box6 = (CheckBox) findViewById(R.id.box6);
		box7 = (CheckBox) findViewById(R.id.box7);
		box8 = (CheckBox) findViewById(R.id.box8);
		box9 = (CheckBox) findViewById(R.id.box9);

		Button courseButton = (Button) findViewById(R.id.button_Course);
		Button unitButton = (Button) findViewById(R.id.button_Unit);
		Button okButton = (Button) findViewById(R.id.up_ok);
		Button cancelButton = (Button) findViewById(R.id.up_cancel);
		courseButton.setOnClickListener(this);
		unitButton.setOnClickListener(this);
		okButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);

		editTextRegInfo[DetailInfo.INFO_COURSE].setEnabled(false);
		editTextRegInfo[DetailInfo.INFO_UNIT].setEnabled(false);
	}

	private void updateView(DetailInfo info) {
		for (int i = 0; i < INFO_END; i++) {
			editTextRegInfo[i].setText(info.getValue(i));
		}
	}

	// when invoke this method, try/catch must be used
	@SuppressLint("NewApi")
	private DetailInfo getInfoFromNetwork() throws JSONException,
			InterruptedException, ExecutionException {
		String jsObj = new MyTask().execute(url + "/get/" + SimpleInfo.localId)
				.get();
		// local id , replace invisible
		jsObj = jsObj.replace(inv, "");
		DetailInfo info = new DetailInfo(jsObj);

		JSONObject js = new JSONObject(jsObj);

		info.ID = SimpleInfo.localId;
		// cannot be null
		info.name = js.getString("givenname");
		info.surName = js.getString("surname");
		info.course = js.getString("course");
		info.unit = js.getString("unit");
		// location
		info.latitude = js.getDouble("latitude");
		info.longitude = js.getDouble("longitude");
		// hobbies & interests

		info.favouriteFood = (!js.getString("foodlike").isEmpty() && !js
				.getString("foodlike").contains(inv)) ? js
				.getString("foodlike") : "...";
		info.favouriteMovie = (!js.getString("movielike").isEmpty() && !js
				.getString("movielike").contains(inv)) ? js
				.getString("movielike") : "...";
		info.favouriteProgremLanguage = (!js.getString("pglanglike").isEmpty() && !js
				.getString("pglanglike").contains(inv)) ? js
				.getString("pglanglike") : "...";
		info.favouriteUnit = (!js.getString("unitlike").isEmpty() && !js
				.getString("unitlike").contains(inv)) ? js
				.getString("unitlike") : "...";
		info.nationNanity = (!js.getString("nationality").isEmpty() && !js
				.getString("nationality").contains(inv)) ? js
				.getString("nationality") : "...";
		info.firstLanguage = (!js.getString("fstlang").isEmpty() && !js
				.getString("fstlang").contains(inv)) ? js.getString("fstlang")
				: "...";
		info.secondLanguage = (!js.getString("sndlang").isEmpty() && !js
				.getString("sndlang").contains(inv)) ? js.getString("sndlang")
				: "...";
		info.address = (!js.getString("suburb").isEmpty() && !js.getString(
				"suburb").contains(inv)) ? js.getString("suburb") : "...";
		info.currentJob = (!js.getString("job").isEmpty() && !js.getString(
				"job").contains(inv)) ? js.getString("job") : "...";
		info.previousJob = (!js.getString("prejob").isEmpty() && !js.getString(
				"prejob").contains(inv)) ? js.getString("prejob") : "...";
		// 17 attributes in total

		// return info
		return info;
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.button_Course:
			selectCourse();
			break;
		case R.id.button_Unit:
			selectUnit();
			break;
		case R.id.up_ok:
			String value;
			for (int i = 0; i < INFO_END; i++) {
				value = editTextRegInfo[i].getText().toString();
				if (value.isEmpty()) {
					if (!checkCanBeNull(i)) {
						Toast.makeText(this, "Input *", Toast.LENGTH_LONG).show();
						setFocus(editTextRegInfo[i]);
					}
				}
				info.SetInfo(i, value);
			}
			ischecked[0] = box0.isChecked() ? true : false;
			ischecked[1] = box1.isChecked() ? true : false;
			ischecked[2] = box2.isChecked() ? true : false;
			ischecked[3] = box3.isChecked() ? true : false;
			ischecked[4] = box4.isChecked() ? true : false;
			ischecked[5] = box5.isChecked() ? true : false;
			ischecked[6] = box6.isChecked() ? true : false;
			ischecked[7] = box7.isChecked() ? true : false;
			ischecked[8] = box8.isChecked() ? true : false;
			ischecked[9] = box9.isChecked() ? true : false;

			if (box0.isChecked())
				info.nationNanity += inv;
			if (box1.isChecked())
				info.firstLanguage += inv;
			if (box2.isChecked())
				info.secondLanguage += inv;
			if (box3.isChecked())
				info.address += inv;
			if (box4.isChecked())
				info.favouriteFood += inv;
			if (box5.isChecked())
				info.favouriteMovie += inv;
			if (box6.isChecked())
				info.favouriteUnit += inv;
			if (box7.isChecked())
				info.favouriteProgremLanguage += inv;
			if (box8.isChecked())
				info.currentJob += inv;
			if (box9.isChecked())
				info.previousJob += inv;

			try {
				String result = new MyTask().execute(url + "/edit",
						info.toJson().toString()).get();
				updateUnits(info.unit);
				Log.i(TAG, result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			finish();

			break;
		case R.id.up_cancel:

			finish();

			break;
		default:
			break;
		}
	}

	private void selectCourse() {
		final String[] items = { "Master of IT Professional",
				"Bachelor of Economics", "Honours Visual Arts",
				"Doctor of Philosophy", "Master of Business", };
		new AlertDialog.Builder(UpdateActivity.this).setTitle("Select Course")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						editTextRegInfo[DetailInfo.INFO_COURSE]
								.setText(items[item]);
					}
				}).show();
	}

	private void selectUnit() {
		final String[] items = { "FIT5046", "FIT5047", "CIF1234", "BSB2234",
				"FIT5167", "FIT5171", "CIF1023", "BSB2342", "CIF6699",
				"BSB1314" };
		new AlertDialog.Builder(UpdateActivity.this)
				.setTitle("Select Unit")
				.setMultiChoiceItems(items, checkResult,
						new DialogInterface.OnMultiChoiceClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {

								checkResult[which] = isChecked;

							}
						})
				.setPositiveButton("Comfirm",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								String showString = "";
								for (int count = 0; count < unitNumber; count++) {
									if (checkResult[count]) {
										showString += (items[count] + ",");
									}
								}
								showString = showString.substring(0,
										showString.length() - 1);
								editTextRegInfo[DetailInfo.INFO_UNIT]
										.setText(showString);
								dialoginterface.dismiss();
							}
						}).show();

	}

	private void updateUnits(String upd) throws JSONException,
			InterruptedException, ExecutionException {
		JSONObject unitPK = new JSONObject();
		JSONObject unit = new JSONObject();
		String units[] = upd.split(",");
		
		String resultD = new MyTask().execute(url3+"/delete/", Integer.toString(SimpleInfo.localId),"detele")
				.get();
		Log.i("remove", resultD);
		for (int i = 0; i < units.length; i++) {
			unit.put("sid", SimpleInfo.localId);
			unit.put("course", units[i]);
			unitPK.put("idUnitsPK", unit);
			String resultP = new MyTask().execute(url3+"/create", unitPK.toString(),"not delete","but post")
					.get();
			Log.i("add new", resultP);
		}
	}
	
	private void setFocus(EditText editText) {
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		editText.requestFocusFromTouch();

	}

	private boolean checkCanBeNull(int index) {
		if ((index == DetailInfo.INFO_NAME)
				|| (index == DetailInfo.INFO_SURNAME)
				|| (index == DetailInfo.INFO_COURSE)
				|| (index == DetailInfo.INFO_UNIT))
			return false;
		return true;
	}

	private class MyTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... prm) {
			// TODO Auto-generated method stub
			if (prm.length == 1)
				return HttpUtils.Get(prm[0]);
			if (prm.length == 2)
				return HttpUtils.Edit(prm[0], prm[1]);
			if (prm.length == 3)
				return HttpUtils.Delete(prm[0], prm[1]);
			if (prm.length == 4)
				return HttpUtils.Post(prm[0], prm[1]);
			else
				return null;
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

}
